package com.ld.collegetask;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.ld.collegetask.beans.BaseJsonBean;
import com.ld.collegetask.beans.DynamicImgBean;
import com.ld.collegetask.databinding.ActivityMemberIdCardBinding;
import com.ld.collegetask.serverInterface.RequestSerives;
import com.ld.collegetask.utils.AppApplication;
import com.ld.collegetask.utils.CameraPopup;
import com.ld.collegetask.utils.DensityUtil;
import com.ld.collegetask.utils.PicassoImageLoader;
import com.ld.collegetask.utils.SharePreference;
import com.squareup.picasso.Picasso;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import me.leefeng.promptlibrary.PromptDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by yilan on 18/3/6.
 */

public class MemberIDCardActivity extends BaseActivity {
    private final String TAG = "MemberEditActivity_2";
    private ActivityMemberIdCardBinding binding;
    private GalleryConfig galleryConfig;
    private List<String> path = new ArrayList<>();
    private ImageView imageView;
    private int biaoji = 0;
    private List<String> markeds;
    private List<String> paths = new ArrayList<>();
    private Integer userId = 0;
    private PromptDialog promptDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_member_id_card);
        //设置标题
        setTitleView(this, binding.ilTitle, true, true, false, false);
        setTitle("身份证认证");
        ico.setVisibility(View.INVISIBLE);
        promptDialog = new PromptDialog(this);
        SharePreference sp = new SharePreference(getBaseContext());
        userId = sp.getUserId();

        showView();
        showData();
    }

    private void showView() {
        binding.imageView1.setOnClickListener(this);
        binding.imageView2.setOnClickListener(this);
        binding.imgX1.setOnClickListener(this);
        binding.imgX2.setOnClickListener(this);
        binding.memberIdCardButton.setOnClickListener(this);
    }

    private void showData() {
        markeds = new ArrayList<>();
        RelativeLayout.LayoutParams para1 = (RelativeLayout.LayoutParams) binding.imageView1.getLayoutParams();
        para1.height = (getResources().getDisplayMetrics().widthPixels / 2 - DensityUtil.dip2px(mActivity,50)) / 8 * 5;
        binding.imageView1.setLayoutParams(para1);

        RelativeLayout.LayoutParams para2 = (RelativeLayout.LayoutParams) binding.imageView2.getLayoutParams();
        para2.height = (getResources().getDisplayMetrics().widthPixels / 2 - DensityUtil.dip2px(mActivity,50)) / 8 * 5;
        binding.imageView2.setLayoutParams(para2);

        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.ld.collegetask.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();
    }

    IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
        @Override
        public void onStart() {
            Log.i(TAG, "onStart: 开启");
        }

        @Override
        public void onSuccess(List<String> photoList) {
            Log.i(TAG, "onSuccess: 返回数据" + photoList.get(0));
            File file = new File(photoList.get(0));
            for (String s : photoList) {
                Log.i(TAG, s);
                markeds.add(s);
            }
            Picasso.with(mActivity)
                    .load(file)
                    .fit()
                    .placeholder(R.drawable.shuohsuojia)
                    .error(R.drawable.shuohsuojia)
                    .into(imageView);
            if (imageView.getId() == R.id.imageView_1){
                binding.imgX1.setVisibility(View.VISIBLE);
            }else {
                binding.imgX2.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "onCancel: 取消");
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "onFinish: 结束");
        }

        @Override
        public void onError() {
            Log.i(TAG, "onError: 出错");
        }
    };

    /**
     * 选择相册、照像机
     */
    private void choosePhotoOrCamera() {
        new CameraPopup(mActivity, imageView, new CameraPopup.OnCallClickEvent() {
            @Override
            public void onCallClick(int position) {
                if (position == 0) {
                    galleryConfig = new GalleryConfig.Builder()
                            .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                            .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                            .provider("com.ld.collegetask.fileprovider")   // provider(必填)
                            .pathList(path)                         // 记录已选的图片
                            .multiSelect(false)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                            .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                            .crop(false, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                            .isShowCamera(false)                     // 是否现实相机按钮  默认：false
                            .filePath("/Gallery/Pictures")          // 图片存放路径
                            .build();
                    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
                                @Override
                                public void permissionGranted(@NonNull String[] permissions) {
                                    if (permissions.length == 1) {
                                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(mActivity);
                                    }
                                }

                                @Override
                                public void permissionDenied(@NonNull String[] permissions) {
                                }
                            }, android.Manifest.permission.WRITE_EXTERNAL_STORAGE
                    );
                } else {
                    PermissionsUtil.requestPermission(getApplication(), new PermissionListener() {
                                @Override
                                public void permissionGranted(@NonNull String[] permissions) {
                                    if (permissions.length == 1) {
                                        GalleryPick.getInstance().setGalleryConfig(galleryConfig).openCamera(mActivity);
                                    }
                                }

                                @Override
                                public void permissionDenied(@NonNull String[] permissions) {
                                }
                            }, android.Manifest.permission.CAMERA
                    );
                }
            }
        });
    }

    @Override
    public void loading() {

    }

    private void member_validateIdentity(String realname,String identitycardnumber,String identitycardobverseimg,String identitycardreverseimg) {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<String> call = requestSerives.member_validate_identity(userId,realname,identitycardnumber,identitycardobverseimg,identitycardreverseimg);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(response.body().toString(), BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    Log.e(TAG, "==" + base.getJson());
                    promptDialog.dismiss();
                    Intent it = new Intent(mActivity, MainActivity.class);
                    setResult(1, it);
                    finish();
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }


    private String dphotos = "";
    private void member_validateImg(File file) {
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("pictureFile", file.getName(), requestFile);

        Retrofit retrofit = new Retrofit.Builder().baseUrl(AppApplication.server).addConverterFactory(ScalarsConverterFactory.create()).build();
        RequestSerives requestSerives = retrofit.create(RequestSerives.class);
        Call<ResponseBody> call = requestSerives.member_validate_img(body);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                String json = "";
                try {
                    json = response.body().source().readString(Charset.forName("UTF-8"));
                    Log.v("Upload",json);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Gson gson = new Gson();
                BaseJsonBean base = gson.fromJson(json, BaseJsonBean.class);
                if ("1".equals(base.getCode())) {
                    DynamicImgBean bean = gson.fromJson(base.getJson(), DynamicImgBean.class);
                    paths.add(bean.getFileUrl());
                    biaoji++;
                    if (markeds.size()!=biaoji){
                        member_validateImg(new File(markeds.get(biaoji)));
                    }else {
                        member_validateIdentity(binding.memberIdCardNameShuru.getText().toString().trim(),
                                binding.memberIdCardIDCardNoShuru.getText().toString().trim(),
                                paths.get(0),
                                paths.get(1));
                    }
                } else {
                    promptDialog.showWarn(base.getMsg());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                promptDialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.imageView_1:
                hideSoftKeyboard();
                imageView = binding.imageView1;
                choosePhotoOrCamera();
                break;
            case R.id.imageView_2:
                hideSoftKeyboard();
                imageView = binding.imageView2;
                choosePhotoOrCamera();
                break;
            case R.id.img_x_1:
                Picasso.with(mActivity)
                        .load(R.drawable.id_no_z)
                        .fit()
                        .placeholder(R.drawable.shuohsuojia)
                        .error(R.drawable.shuohsuojia)
                        .into(binding.imageView1);
                binding.imgX1.setVisibility(View.GONE);
                break;
            case R.id.img_x_2:
                Picasso.with(mActivity)
                        .load(R.drawable.id_no_f)
                        .fit()
                        .placeholder(R.drawable.shuohsuojia)
                        .error(R.drawable.shuohsuojia)
                        .into(binding.imageView2);
                binding.imgX2.setVisibility(View.GONE);
                break;
            case R.id.member_id_card_button:
                if (binding.memberIdCardNameShuru.getText().toString().trim().equals("")){
                    promptDialog.showWarn("请填写真实姓名");
                    break;
                }
                if (binding.memberIdCardIDCardNoShuru.getText().toString().trim().equals("")){
                    promptDialog.showWarn("请填写身份证号码");
                    break;
                }
                if (markeds.size()!=2){
                    promptDialog.showWarn("请选择身份证照片");
                    break;
                }
                hideSoftKeyboard();
                promptDialog.showLoading("正在提交");
                    biaoji = 0;
                member_validateImg(new File(markeds.get(biaoji)));
                break;
        }
    }
}
